#include "px_filebin.h"
#include <stdio.h>
#define  NULL 0
unsigned char readByte( FileBin * fbin )
{
	if( fbin->peek_cur >= fbin->peek_end)
	{
		return -1;
	}

	return fbin->f[fbin->peek_cur++] ;
}

short readShort( FileBin * fbin )
{
	short temp=0;
	if( fbin->peek_cur >= fbin->peek_end)
	{
		return -1;
	} 
	temp = (fbin->f[fbin->peek_cur] << 8) | fbin->f[fbin->peek_cur + 1];
	fbin->peek_cur += 2;

	return temp;
}

int readInt(FileBin * fbin)
{
	int temp=0;
	if( fbin->peek_cur >= fbin->peek_end)
	{
		return -1;
	}
	temp = fbin->f[fbin->peek_cur+3] << 24 | fbin->f[fbin->peek_cur + 2] << 16 | fbin->f[fbin->peek_cur + 1] << 8 | fbin->f[fbin->peek_cur];
	fbin->peek_cur += 4;
	return temp;
}

char* readString( FileBin * fbin )
{
	int p = fbin->peek_cur;
    int size = 0;
	char* temp =NULL;
	if( fbin->peek_cur >= fbin->peek_end)
	{
		return NULL;
	}	
	while(fbin->f[p])
	{
		size++;
		p++;
	}
    temp = (char *) malloc(size + 1);
	memcpy(temp, &fbin->f[fbin->peek_cur], size);
	temp[size] = '\0';
	fbin->peek_cur += size + 1;
	return temp;
}

char * readString_1(FileBin * fbin)
{
	int size = 0;
	char* temp =NULL;
	int p = fbin->peek_cur;
	if( fbin->peek_cur >= fbin->peek_end)
	{
		return NULL;
	}	
	size = fbin->f[p];
    temp = (char *) malloc(size + 1);
	memcpy(temp, &fbin->f[fbin->peek_cur]+1, size);
	temp[size] = '\0';
	fbin->peek_cur += size + 1;
	return temp;
}
int readData( FileBin * fbin ,char *data , int length )
{
	int len;
	if( length == 0 || fbin->peek_cur >= fbin->peek_end) 
	{
		return -1;
	}


	if(fbin->peek_cur + length > fbin->peek_end)
	{
		len = fbin->peek_end - fbin->peek_cur;
		memcpy(data , &fbin->f[fbin->peek_cur], len);

		fbin->peek_cur += len;

		return len;
	}
	else
	{
		memcpy(data, &fbin->f[fbin->peek_cur], length);

		fbin->peek_cur += length;
		return length;
	}
}

char* readUTF(  FileBin * fbin )
{
	short  size = readShort(fbin);
	fbin->peek_cur += size;
}

FileBin * init_fileBin( const char * fileName )
{
	FILE *fp = fopen(fileName, "rb");
	FileBin * fBin = (FileBin *)malloc(sizeof(FileBin));
	unsigned long size;
	if(fp == NULL)
	{
		free(fBin);
		return NULL;
	}
	fseek(fp,0,SEEK_END);
	size = ftell(fp);
	fseek(fp,0,SEEK_SET);
	fBin->f = (char * ) malloc(size);
	size = fread(fBin->f,sizeof(unsigned char), size,fp);
	fclose(fp);
	fBin->peek_end = size;
	fBin->peek_cur = 0;		
}

